package com.hk.commons.poi.excel.read.sax;

import com.hk.commons.poi.excel.exception.InvalidCellReadableExcelException;
import com.hk.commons.poi.excel.metadata.InvalidCell;
import com.hk.commons.poi.excel.metadata.ReadWorkbook;
import com.hk.commons.poi.excel.read.AbstractExcelReadExecutor;
import com.hk.commons.util.PropertyAccessorUtils;

import java.util.ArrayList;


/**
 * @param <T>
 * @author Kevin
 */
public abstract class SaxAbstractExcelReadExecutor<T> extends AbstractExcelReadExecutor<T> {

    protected SaxAbstractExcelReadExecutor(ReadWorkbook readWorkbook) {
        super(readWorkbook);
    }

    /**
     * 将读取的数据转换为对象
     *
     * @param readContext readContext
     * @param row         rowNum
     * @return 解析的数据
     */
    @SuppressWarnings("unchecked")
    protected T readRow(ReadContext readContext, int row) {
        var beanWrapper = PropertyAccessorUtils.forBeanPropertyAccess(readWorkbook.getBeanClass());
        var columnValueMap = readContext.getColumnValueMap();
        var titleList = readContext.getTitleList();
        var invalidCellList = new ArrayList<InvalidCell>();
        columnValueMap.forEach((key, value) -> {
            var title = titleList.get(key.intValue());
            try {
                beanWrapper.setPropertyValue(title.getPropertyName(), trimToValue(value));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                invalidCellList.add(new InvalidCell(row, key.intValue(), value, title, STR."\{value} 设置失败,原因:\{e.getMessage()}"));
            }
        });
        if (!invalidCellList.isEmpty()) {
            throw new InvalidCellReadableExcelException("设置属性失败", beanWrapper.getWrappedInstance(), invalidCellList);
        }
        return (T) beanWrapper.getWrappedInstance();
    }
}
